package cn.itcast.handler;

import cn.itcast.message.GroupChatRequestMessage;
import cn.itcast.message.GroupChatResponseMessage;
import cn.itcast.server.session.GroupSession;
import cn.itcast.server.session.GroupSessionFactory;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * @Name: GroupChatRequestMessageHandler
 * @Description: 群聊天handler
 * @Author: Mr.Tong
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String from = msg.getFrom();
        String content = msg.getContent();
        //获取群组成员的channel
        GroupSession groupSession = GroupSessionFactory.getGroupSession();
        List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
        //遍历channel发送消息
        membersChannel.forEach(channel -> channel.writeAndFlush(new GroupChatResponseMessage(from, content)));
        //告诉用户发送成功
        ctx.channel().writeAndFlush(new GroupChatResponseMessage(true, "发送消息成功"));

    }
}
